import { Context } from 'koa';
import { UserService } from '../../services/system/userService';
import { createError } from '../../middleware/errorHandler';
import { CreateUserDto, UpdateUserDto } from '../../dtos/system/UserDto';
import { generateResponse } from '../../utils';

export class UserController {
  private userService: UserService;

  constructor() {
    this.userService = new UserService();
  }

  // 获取所有用户
  getUsers = async (ctx: Context): Promise<void> => {
    try {
      let data = ctx.request.body as any
      let users = [] as any
      if (data?.page && data?.limit) {
        // const users = await this.userService.getAllUsers(ctx.request.body.page, ctx.request.body.limit);
        users = await this.userService.getUsersWithPagination(data.page, data.limit);
        console.log(users, 'users');
      } else {
        users = await this.userService.getAllUsers();
      }


      generateResponse(ctx, users);
    } catch (error: any) {
      throw createError('获取用户列表失败', 500, error);
    }
  };

  // 根据ID获取用户
  getUserById = async (ctx: Context): Promise<void> => {
    try {
      const { id } = ctx.params;
      const user = await this.userService.getUserById(id);
      if (!user) {
        throw createError('用户不存在', 404);
      }
      generateResponse(ctx, user);
    } catch (error: any) {
      if (error.status === 404) throw error;
      throw createError('获取用户信息失败', 500, error);
    }
  };

  // 创建用户
  createUser = async (ctx: Context): Promise<void> => {
    try {
      // 从验证中间件获取已验证的数据
      const userData = ctx.state.validatedData as CreateUserDto;
      const user = await this.userService.createUser(userData);
      generateResponse(ctx, user, '用户创建成功');
    } catch (error: any) {
      throw createError('创建用户失败1', 400, error);
    }
  };

  // 更新用户
  updateUser = async (ctx: Context): Promise<void> => {
    try {
      const { id } = ctx.params;
      // 从验证中间件获取已验证的数据
      const userData = ctx.state.validatedData as UpdateUserDto;

      const user = await this.userService.updateUser(id, userData);

      if (!user) {
        throw createError('用户不存在', 404);
      }
      generateResponse(ctx, user, '用户更新成功');
    } catch (error: any) {
      if (error.status === 404) throw error;
      throw createError('更新用户失败', 400, error);
    }
  };

  // 删除用户
  deleteUser = async (ctx: Context): Promise<void> => {
    try {
      const { id } = ctx.params;
      const result = await this.userService.deleteUser(id);

      if (!result) {
        throw createError('用户不存在', 404);
      }
      generateResponse(ctx, null, '用户删除成功');
    } catch (error: any) {
      if (error.status === 404) throw error;
      throw createError('删除用户失败', 500, error);
    }
  };
}